#!/opt/local/bin/node

var config = require('./configController');
var helper = require('./helper');
var presets = require('./presetsController');
var logger = require('./logger');

/* change logfile to include date */
logger.log2FileAddDate();

/* say hello */
logger.info('#### PresStore Media Converter '+config.read('version')+' ####');

/* release root permissions */
if (!helper.setUser(config.read('expectedUID'))) {
	process.exit(1);
};

/* get source file path */
var source = helper.checkArgsAndGetSource();
if (source==undefined) {
	process.exit(1);
}
logger.debug('Source file: '+source);

/* check if source is valid */
var exists = helper.fileExists(source);
if (!exists) {
	logger.error('Source file '+source+' doesn\'t exist or is not accessable');
	process.exit(1);
}

/* get source file type */
var type = helper.getFileType(source);
if (type==undefined) {
	process.exit(1);
}
logger.debug('Source file type: '+type);

/* get preset object for file type */
var preset = presets.getPresets(type);
if (typeof preset == 'undefined' || preset.length==0) {
	process.exit(1);
}

/* generate temp file name */
var destination_template = '/tmp/'+helper.getHash();
logger.debug('Temp destination template path: '+destination_template);

/* execute converter and check result */
presets.executePresets(preset,source,destination_template, function(result) {
	if (result===false || !helper.fileExists(result)) {
		logger.error('Error while creating '+destination_template+' from '+source);
		process.exit(1);
	}
	
	/* exit */
	logger.error(result);
	process.exit(0);
});